import QtQuick 2.11
import QtQuick.Window 2.3
import QtQuick.Dialogs 1.2
import QtMultimedia 5.9

//import QtQuick.Controls.Material 2.2


import cn.leamus.gamedata 1.0


//import "."
import "qrc:/QML"
import _Global 1.0
import _Global.Popup 1.0
import _Global.Button 1.0
import _Global.Particles 1.0


import ".."

//import "../_Global/Global.js" as GlobalJS
import "GameJS.js" as GameJS




Item {
    id: root

    signal close();

    //初始化，游戏启动时由 C++ Manager 调用
    function initOnce(param) {

        //console.debug("param:",typeof(param) , param, param.length);
        //Leamus:
        //Global.data.myPets = [new GameJS.ClassPet()]
        //Global.data.enemyPets = [new GameJS.ClassPet()]
        //Global.data.friendPets = [new GameJS.ClassPet()]

        GameManager.s_qml_DebugMsg.connect(debugWindow.item.showDebugMsg);


        GameManager.s_qml_UpdateInfo.connect(function(url, type) {

            var tMsg = qsTr("<a href='%1'><h2>有新版本，点此升级</h2></a>").arg(url);
            var tErrorMsg;

            switch(type) {
            case 0:
                //gameMsgBoxVersion.text = msg;
                //gameMsgBoxVersion.showMsg(true,false);
                //login.item.enableLogin();
                login.item.serverResponseMsg("");

                console.debug("[game]s_qml_UpdateInfo", url, type);
                break;
            case 1:
                gameMsgBoxVersion.text = tMsg;
                gameMsgBoxVersion.showMsg(true,false);
                login.item.serverResponseMsg("");

                console.debug("[game]s_qml_UpdateInfo", url, type);
                break;
            case 2:
                gameMsgBoxVersion.text = tMsg;
                gameMsgBoxVersion.showMsg(false,true);

                console.debug("[game]s_qml_UpdateInfo", url, type);
                break;
            case -1:
                tErrorMsg = qsTr("<a href='%1'><h2>版本居然比服务器的新，点此跳转</h2></a>").arg(url);
                gameMsgBoxVersion.text = tErrorMsg;
                gameMsgBoxVersion.showMsg(true,true);
                login.item.serverResponseMsg("版本居然比服务器的新");

                console.debug("[game]s_qml_UpdateInfo", url, type);
                break;
            case -2:
            case -3:
                tErrorMsg = qsTr("<a href='%1'><h2>版本检测出错，请退出或点此升级后重试</h2></a>").arg(url);
                console.debug(gameMsgBoxVersion)
                gameMsgBoxVersion.text = tErrorMsg;
                gameMsgBoxVersion.showMsg(false,true);

                console.error("[!game]s_qml_UpdateInfo type ERROR:", url, type);
                break;
            default:
                gameMsgBoxVersion.text = tMsg;
                gameMsgBoxVersion.showMsg(false,true);

                console.error("[!game]s_qml_UpdateInfo type ERROR:", url, type);
            }

            if(Platform.compileType() === "debug") {
                gameMsgBoxVersion.showMsg(true,true);
                //login.item.serverResponseMsg("--内测版--");
                return;
            }
        });



        GameManager.s_qml_GameOver.connect(function(status, code) {
            _private.gameOver(status, code);
        });


        GameManager.s_qml_GameDisconnected.connect(function(code) {

            console.debug("[game]游戏服务器断开:", code);
            if(GameCore.gameStatus == GameCoreClass.Game_Status_Running) {

                if(GameCore.netPlay == true) {
                    UserInfo.sl_qml_ChoiceGameServer(UserInfo.serverID);
                }
            }
            else {
                GameCore.sl_OverGame(GameCoreClass.Game_Status_Terminated, 88);
            }
        });
        /*
        GameManager.s_qml_GameStart.connect(function(){

            //gameUI.focus = true;
            _private.gameStart();
        });*/




        GameManager.s_qml_JoinGroup.connect(function(groupID, bRunning, success, code) {
            if(success === true) {
                console.debug("[game]s_qml_JoinGroup", groupID, bRunning);

                gameInGroup.item.nGroupID = groupID;
                gameInGroup.item.clearMsg();
                gameInGroup.visible = true;
                gameInGroup.focus = true;

                gameInGroup.item.refresh();
            }
            else
                console.error("[!game]JoinGroup ERROR:", code);
        });

        GameManager.s_qml_ReJoinRunningGroup.connect(function(socketID, oldSocketID, groupIndex, success, code) {
            if(success === true) {
                console.debug("[game]s_qml_ReJoinRunningGroup", socketID, oldSocketID);


                gameInGroup.item.nGroupID = GameCore.socketInfo.groupID;
                gameInGroup.item.clearMsg();
                gameInGroup.visible = true;
                gameInGroup.focus = true;

                gameInGroup.item.refresh();


                fightUI.item.reJoinRunningGroup(socketID, groupIndex);
            }
            else
                console.error("[!game]s_qml_ReJoinRunningGroup ERROR:", code);
        });

        GameManager.s_qml_OthersJoinGroup.connect(function(playerInfo,bRunning,bResetFrame,bIn,bKeepGroupIndex) {
            if(bRunning === true) {
                if(bIn === true) {
                    console.debug("%1 加入Playing房间".arg(playerInfo.nickname));
                }
                else {
                    if(bKeepGroupIndex) {
                        console.debug("%1 退出Playing房间(断线)".arg(playerInfo.nickname));
                    }
                    else {
                        delete Global.gameData.shareGameData.players[playerInfo.userGameID];
                        console.debug("%1 退出Playing房间".arg(playerInfo.nickname));
                    }
                }

                fightUI.item.playerJoinGroup(playerInfo,bRunning,bResetFrame,bIn,bKeepGroupIndex);
            }
            else {
                gameInGroup.item.playerJoinGroup(playerInfo,bIn);

                gameInGroup.item.refresh();
            }

        });

        GameManager.s_qml_OthersReJoinRunningGroup.connect(function(socketID, oldSocketID, groupIndex, userGameID, bRunning, bResetFrame, bIn) {
            if(bRunning === true) {
                if(bIn === true) {
                    //Global.gameData.shareGameData.players[socketID] = Global.gameData.shareGameData.players[oldSocketID];
                    //delete Global.gameData.shareGameData.players[oldSocketID];

                    console.debug("s_qml_OthersReJoinRunningGroup",socketID,oldSocketID, groupIndex, userGameID,bRunning,bResetFrame,bIn);
                    fightUI.item.othersReJoinRunningGroup(socketID, groupIndex, userGameID);
                }
                else {
                    console.debug("s_qml_OthersReJoinRunningGroup1",socketID,oldSocketID, groupIndex, userGameID,bRunning,bResetFrame,bIn);
                }
            }
            else {
                console.debug("s_qml_OthersReJoinRunningGroup2",socketID,oldSocketID, groupIndex, userGameID,bRunning,bResetFrame,bIn);
            }

        });

        GameManager.s_qml_SetMaster.connect(function(playerInfo, bMaster, bRunning, bAllDataIsEmpty, success, code) {
            if(bRunning === true) {
                if(success) {
                    if(playerInfo.userGameID === UserInfo.userGameID) {
                        console.debug("[game]你是房间管理了!");
                        if(bAllDataIsEmpty === true)
                            Global.gameFunctions.sendGameSyncAllData();
                    }

                    fightUI.item.setMaster(playerInfo,bMaster,bRunning,bAllDataIsEmpty);
                }
                else
                    console.warn("[!game]SetMaster WARNING:", code);
            }
            else {
                if(success) {
                    gameInGroup.item.refresh();
                }
                else
                    console.warn("[!game]SetMaster WARNING:", code);
            }

        });

        GameManager.s_qml_GetReady.connect(function(playerInfo,success,code) {
            if(success) {
                //gameInGroup.item.playerJoinGroup(playerInfo,bIn);

                if(code === 2)
                    gameInGroup.item.appendText(playerInfo.nickname + " 准备");
                else if(code === 1)
                    gameInGroup.item.appendText(playerInfo.nickname + " 取消准备");
                else
                    gameInGroup.item.appendText(playerInfo.nickname + " 干了个啥ERROR?" + code);

                gameInGroup.item.refresh();
            }
            else
                console.warn("[!game]GetReady WARNING:", code);
        });

        GameManager.s_qml_ExitGroup.connect(function(success,code) {
            if(success) {
                //gameInGroup.item.refresh();
                console.debug("[game]退出成功");
            }
            else
                console.error("[!game]ExitGroup ERROR:", code);
        });

        /*GameManager.s_qml_OthersReadyInGroup.connect(function(playerInfo,status) {

            gameInGroup.item.refresh();
        });*/

        //聊天
        GameManager.s_qml_OthersMessage.connect(function(userGameID,type,message) {
            switch(type) {
            case 1:
                //gameUI.item.showPlayerMsg(type,message);
                break;
            default:
                console.error("[!game]s_qml_OthersMessage type ERROR:", type);
            }
        });




        GameManager.s_SetClientShareExtraGameData.connect(function(code, successed) {
            if(successed) {
                console.debug("[game]更新用户共享额外信息完毕");
            }
            else
                console.error("[!game]s_SetClientShareExtraGameData ERROR:", code);
        });







        GameManager.s_GameTransferData.connect(function(userGameID, data) {
            console.debug("[game]GameTransferData:", JSON.stringify(data,null,1));
            //console.debug("TransferGameMessage:", data, Object.keys(data));



            fightUI.item.gameTransferData(data);

        });

        GameManager.s_GameFrameData.connect(function(frameIndex, data) {
            console.debug("[game]GameFrameData:", frameIndex, JSON.stringify(data,null,1));
            //console.debug("TransferGameMessage:", data, Object.keys(data));

            console.debug("[game]GameFrameData1")
            if(Global.gameData.nGameFrameIndex !== frameIndex) {
                console.error("[!game]FrameIndex ERROR:", frameIndex, Global.gameData.nGameFrameIndex);
            }
            console.debug("[game]GameFrameData2")
            GameManager.showPlayersInfo();
            console.debug("[game]GameFrameData3")

            //脏数据过滤
            for(var dd in data) {
                //if(mapPlayerChangeSocketIDCache[data[dd]["__SocketID"]] !== undefined) {
                //    data[dd]["__SocketID"] = mapPlayerChangeSocketIDCache[data[dd]["__SocketID"]];
                //}
                //if(GameManager.getPlayerInfo(data[dd]["__UserGameID"]) === null) {
                if(GameManager.getPlayerInfo(data[dd]["__GroupIndex"]) === null) {

                    console.debug("[game]s_GameFrameData脏数据过滤:",data[dd]);
                    console.debug(dd,JSON.stringify(data[dd]),data[dd]["__GroupIndex"],GameManager.getPlayerInfo(data[dd]["__UserGameID"]));
                    delete data[dd];
                }
            }


            if(fightUI.item.gameFrameData(frameIndex, data)) {
                if(GameCore.socketInfo.isGroupMaster) {
                    Global.gameFunctions.sendGameSyncAllData();
                }
            }

            Global.gameData.nGameFrameIndex++;
            Global.gameData.nGameFrameSendCount = 0;
        });

        GameManager.s_GameSyncData.connect(function(userGameID, data) {
            console.debug("[game]GameSyncData:", data, data["__UserGameID"], JSON.stringify(data,null,1));

            //检测玩家是否退出
            if(data["__SocketID"] === -1 || (data["__Type"] === 0 && data["__Value"] === 1)) {
                delete Global.gameData.shareGameData.players[data["__UserGameID"]];
            }
            else {
                Global.gameData.shareGameData.players[data["__UserGameID"]] = data;
                fightUI.item.gameSyncData(data);
            }

            //console.debug("TransferGameMessage:", data, Object.keys(data));
        });

        GameManager.s_GameSyncAllData.connect(function(frameIndex, sendFrameCount, data, listData) {
            console.debug("[game]GameSyncAllData:", JSON.stringify(data,null,1), JSON.stringify(listData,null,1));

            Global.gameData.nGameFrameSendCount = sendFrameCount;


            for(var dd in data.players) {

                //脏数据过滤
                if(GameManager.getPlayerInfo(data.players[dd]["__GroupIndex"]) === null) {
                    console.debug("[game]s_GameSyncAllData脏数据过滤:",data.players[dd]);
                    delete data.players[dd];
                }
            }


            Global.gameData.nGameFrameIndex = frameIndex;
            Global.gameData.shareGameData = data;


            for(var dd in listData) {
                console.debug("[game]s_GameSyncAllData:", listData[dd], listData[dd]["__UserGameID"]);

                //脏数据过滤
                if(GameManager.getPlayerInfo(listData[dd]["__GroupIndex"]) === null) {
                    console.debug("[game]s_GameSyncAllData脏数据过滤:",listData[dd]);
                    delete listData[dd];
                }


                Global.gameData.shareGameData.players[listData[dd]["__UserGameID"]] = listData[dd];
            }


            fightUI.item.gameSyncAllData(frameIndex, data, listData);


            //console.debug("TransferGameMessage:", data, Object.keys(data));
        });






        UserInfo.s_loginStatus.connect(function(code) {     //用户登录
            switch(code) {
            case 0:
                console.debug("[game]登录成功");
                break;
            default:
                console.error("[!game]登录失败:",code);
            }

        });
        UserInfo.s_regStatus.connect(function(code) {       //用户注册
            switch(code) {
            case 0:
                console.debug("[game]注册成功");
                break;
            case 1:
                console.debug("[game]注册名重复");
                break;
            default:
                console.error("[!game]注册失败:",code);
            }
        });

        UserInfo.s_gameServerInfoStatus.connect(function(code) {
            switch(code) {
            case 0:
                console.debug("[game]获取GameServer成功");
                if(UserInfo.gameServerInfo.length === 1) {
                    console.debug("[game]GameServers:", JSON.stringify(UserInfo.gameServerInfo));
                    UserInfo.sl_qml_ChoiceGameServer(1);
                }
                else {
                    console.debug("[game]GameServers:", JSON.stringify(UserInfo.gameServerInfo));
                    UserInfo.sl_qml_ChoiceGameServer(1);
                }

                break;
            default:
                console.error("[!game]获取GameServer失败:",code);
            }
        });



        UserInfo.s_loginGameServerStatus.connect(function(code) {     //用户登录游戏服务器
            //console.debug("login status:")
            switch(code) {
            case 0:
                _private.loginOver();

                break;
            case 1: //没有此用户
                console.debug("[game]需要注册GameServer!");
                registerGameUser.visible = true;
                break;
            case 2: //密码错误
                login.item.showErr("用户名或密码错误");
                break;
            default:
                login.item.showErr("服务器出错");
            }
        });

        UserInfo.s_regGameServerStatus.connect(function(code) {   //用户注册游戏服务器
            //console.debug("reg status:")
            switch(code) {
            case 0:
                login.visible = false;
                register.visible = false;
                normalUI.visible = true;
                normalUI.focus = true;
                normalUI.item.resume();

                console.debug("[game]注册GameServer成功!")

                GameManager.sl_qml_GetGameDataToNetDB("", 1, GameManagerClass.DataType_JSon_Info, _private.getGameDataToNetDBCallback);

                break;
            case 1:
                console.warn("[game]名称已被注册")
                register.item.showErr("[game]名称已被注册");
                break;
            case 2:
                console.warn("[game]名称不符合")
                register.item.showErr("[game]名称不符合");
                break;
            case 3:
                console.warn("[game]名称有禁词")
                register.item.showErr("[game]名称有禁词");
                break;
            default:
                login.item.showErr("服务器出错");
            }

            //gameClass.item.createLevels(1)
        });



        GameCore.s_InitOnceFinished.connect(function() {
            //gameUI.item.initOnce();
            normalUI.item.initOnce();
            fightUI.item.initOnce();
        });
        GameCore.s_GameInitFinished.connect(function() {

            _private.init();
        });
        GameCore.s_GameStart.connect(function(isStarted) {

            _private.gameStart(isStarted);
        });

    }


    anchors.fill: parent
    visible: true
    //focus: true

    //屏幕自适应方法1：动态缩放，优点：图片不失真，字体正常；缺点：需要绑定，速度较慢
    Item {
        id: itemRoot
        focus: true
        anchors.fill: parent

        //登录窗口
        Loader {
            id: login
            source: "Client/Login.qml"
            anchors.fill: parent
            //width: 800
            //height: 600
            //focus: true
            z: 10

            Connections {
                target: login.item
                onS_forgot: {
                    Qt.openUrlExternally(GameJS.urlForgot)
                }
                onS_minimized: {
                    root.visibility = Window.Minimized
                }
                onS_login: {
                    GameManager.userInfo.sl_qml_UserLogin(param);
                }

                onS_reg: {
                    login.visible = false;
                    register.visible = true;
                    register.focus = true;
                    //Qt.openUrlExternally(GameJS.urlRegisterUser)
                }
            }
        }

        //注册窗口
        Loader {
            id: register
            source: "Client/Register.qml"
            anchors.fill: parent
            //width: 800
            //height: 600
            visible: false
            z: 10

            Connections {
                target: register.item
                onS_RegUser: {
                    GameManager.userInfo.sl_qml_UserReg(param);
                }
                onS_Close: {
                    register.visible = false;
                    login.visible = true;
                    login.focus = true;
                }
            }
        }

        //注册窗口
        Loader {
            id: registerGameUser
            source: "Client/RegisterGameUser.qml"
            anchors.fill: parent
            //width: 800
            //height: 600
            visible: false
            z: 10

            Connections {
                target: registerGameUser.item
                onS_RegGameUser: {
                    UserInfo.sl_qml_GameUserReg(param);
                }
            }
        }

        //游戏界面
        Loader {
            //property int interger

            id: gameUI
            //source: "GameUI.qml"
            anchors.fill: parent
            //width: 800
            //height: 600
            visible: false
            //focus: true
            z: 100

            Connections {
                target: gameUI.item

                onS_closeGameUI: {
                    gameUI.visible = false;
                    gameClass.visible = true
                }
                onS_debugMsg: debugWindow.item.showDebugMsg(msg)

            }
        }

        //Normal界面
        Loader {
            id: normalUI
            source: "NormalUI.qml"
            anchors.fill: parent
            //width: 800
            //height: 600
            visible: false
            z: 110

            Connections {
                target: normalUI.item

                onS_encounterEnemy: {
                    GameManager.sl_StartGame(false);
                }

                onS_CreateGroup: {
                    //normalUI.visible = false;
                    normalUI.item.pause();
                    gameGroup.visible = true;
                    console.debug("[game]CreateGroup")
                }
            }
        }



        //Group界面
        Loader {
            id: gameGroup
            source: "Group/Group.qml"
            anchors.fill: parent
            //width: 800
            //height: 600
            visible: false
            z: 130

            Connections {
                target: gameGroup.item

                onS_CreateGroup: {
                    GameManager.sl_Server_CreateGroup(playerMaxCount,playerWatchingMaxCount,password,groupType,data);
                }
                onS_JoinGroup: {
                    GameManager.sl_Server_JoinGroup(groupID,password,forceJoin,joinType,groupType);
                }
                onS_Close: {
                    gameGroup.visible = false;
                }
            }
        }
        //竞技游戏房间窗口
        Loader {
            id: gameInGroup
            source: "Group/InGroup.qml"
            anchors.fill: parent
            visible: false
            z: 131

            Connections {
                target: gameInGroup.item
                onS_GameReady: {
                    GameManager.sl_Server_GetReady(duiwu);
                }
                onS_StartGame: {
                    GameManager.sl_Server_StartGame();
                }
                onS_ExitGroup: {
                    GameManager.sl_Server_ExitGroup();
                    gameGroup.visible = true;
                    gameGroup.focus = true;
                    gameInGroup.visible = false;
                }
                /*onShowConfig: {
                    menuConfig.show();
                }*/

            }
        }



        //Fight界面
        Loader {
            id: fightUI
            source: "FightUI.qml"
            anchors.fill: parent
            //width: 800
            //height: 600
            visible: false
            z: 140

            Connections {
                target: fightUI.item

                /*onSendGameFrameData: {
                    _private.sendGameFrameData(frameData);
                }
                onSendGameSyncData: {
                    _private.sendGameSyncData(syncData);
                }*/
            }
        }



        //调试窗口
        Loader {
            id: debugWindow
            property int contentOr: 0
            source: "DebugWindow.qml"
            anchors.fill: parent
            //width: 800
            //height: 600
            visible: false
            z: 900

            Connections {
                target: debugWindow.item

                onDebugGameManager: GameManager.sl_qml_DebugButton(value,param)
                onDebugGameCore: GameCore.sl_qml_DebugButton(type,v)
                onDebugGameWindow: {
                    switch(value) {
                    case 1:
                        break;
                    case 2: //测试屏幕
                        if(debugWindow.contentOr == 0) {
                            root.contentOrientation = Qt.PrimaryOrientation
                            debugWindow.contentOr ++
                        }
                        else if(debugWindow.contentOr == 1) {
                            root.contentOrientation = Qt.LandscapeOrientation
                            debugWindow.contentOr ++
                        }
                        else if(debugWindow.contentOr == 2) {
                            root.contentOrientation = Qt.PortraitOrientation
                            debugWindow.contentOr ++
                        }
                        else if(debugWindow.contentOr == 3) {
                            root.contentOrientation = Qt.InvertedLandscapeOrientation
                            debugWindow.contentOr ++
                        }
                        else if(debugWindow.contentOr == 4) {
                            root.contentOrientation = Qt.InvertedPortraitOrientation
                            debugWindow.contentOr = 0
                        }
                        break;

                    default:
                        console.debug(value, param);
                        break;
                    }

                }
            }
        }



        //游戏消息（广播）
        MsgBox {
            id: gameMsgBox
            z: 901

            width: Global.dpW(200)
            height: Global.dpH(200)
            anchors.verticalCenter: parent.verticalCenter
            anchors.horizontalCenter: parent.horizontalCenter

            visible: true

            function showMsg(p1,p2) {

            }
            MouseArea {
                anchors.fill: parent
                onClicked: gameMsgBox.visible = false;
            }
        }

        //升级信息
        MsgBox {
            id: gameMsgBoxVersion
            z: 902

            width: Global.dpW(200)
            height: Global.dpH(200)
            anchors.verticalCenter: parent.verticalCenter
            anchors.horizontalCenter: parent.horizontalCenter

            visible: true

            function showMsg(p1,p2) {

            }
            MouseArea {
                anchors.fill: parent
                onClicked: gameMsgBoxVersion.visible = false;
            }
        }


        Rectangle {
            width: 20
            height: 20
            //x: 0
            //y: 0
            z: 910
            anchors.right: parent.right
            anchors.top: parent.top

            Text {
                text: qsTr("调试")
            }

            MouseArea {
                anchors.fill: parent
                onClicked: {
                    if(debugWindow.visible == false) {
                        debugWindow.visible = true
                    }
                    else {
                        debugWindow.visible = false
                    }
                    //console.debug(debugWindow.visible)
                }
            }
        }



        //结束对话框(Esc)
        Popup {
            id: menuEsc
            //x: 200; y: 180
            z: 2000
            anchors.fill: parent
            //width: 800
            //height: 600
            //innerWidth: 400
            //innerHeight: 300
            color: 'lightgreen'
            visible: false
            showMask: true
            showingAnimationType: "fade"
            showingEasingType: Easing.Linear
            showingDuration: 200
            radius: 5           //圆角
            maskParent: parent
            maskColor: 'lightgrey'
            maskOpacity: 0.5

            Rectangle {
                x: 10
                y: 150
                width: 150
                height: 80
                color: "gray"

                Text {
                    text: qsTr("退出")
                }

                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        Qt.quit();
                    }
                }
            }

            Rectangle {
                x: 200
                y: 150
                width: 150
                height: 80
                color: "gray"

                Text {
                    text: qsTr("取消")
                }

                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        menuEsc.hide()
                        //menuEsc.focus = false;
                    }
                }
            }

            Keys.onEscapePressed:  {
                menuEsc.hide();
                itemRoot.focus = true;
                //menuEsc.hide();
                event.accepted = true;
            }
            Keys.onBackPressed: {
                menuEsc.hide();
                itemRoot.focus = true;
                //menuEsc.hide();
                event.accepted = true;
            }
        }



        Particles1 {
            id: particles
            source: Global._FixResourcePath_R("Media/Images/Snow.png")
            z: 999
            anchors.fill: parent
            emitter {
                size: Global.dpH(30)
                sizeVariation: Global.dpH(10)
            }
            particle {
                blueVariation: 0
                colorVariation: 0.1
            }
        }


        Keys.onPressed:  {
            console.debug("[game1]Keys.onPressed:", event.key, itemRoot.focus, root.focus)
            event.accepted = false;
        }

    }


    Keys.onEscapePressed:  {
        console.debug("[game]Keys.onEscapePressed:", event.key)
        event.accepted = true;
        _private.exit();
    }
    Keys.onBackPressed: {
        console.debug("[game]Keys.onBackPressed:", event.key)
        event.accepted = true;
        _private.exit();
    }

    Keys.onPressed:  {
        console.debug("[game]Keys.onPressed:", event.key, itemRoot.focus, root.focus)
        event.accepted = false;
    }


    /*Component {
        id: petComp
        Pet {
            / *
            mouseArea.onEntered: if(bEnable){scale = 1.03; z += 1;}
            mouseArea.onExited: {
                if(bEnable){scale = 1; z -= 1;}
                rectPokeTips.visible = false;* /
        }
    }*/

    QtObject {  //私有数据,函数,对象等
        id: _private

        function loginOver() {
            if(GameCore.socketInfo.groupID === -1) {
                login.visible = false;
                register.visible = false;
                normalUI.visible = true;
                normalUI.focus = true;
                normalUI.item.resume();

                console.debug("[game]loginOver");
                GameManager.sl_qml_GetGameDataToNetDB("", 1, GameManagerClass.DataType_JSon_Info, _private.getGameDataToNetDBCallback);

            }
            else {
                console.debug("[game]loginOver2");
                GameManager.sl_qml_ReJoinRunningGroup();
            }
        }

        function init() {
            Global.gameData.nGameFrameSendCount = 0;
            Global.gameData.nGameFrameIndex = 0;
            //Master必须要把所用的Data初始化，因为要给其他客户传输
            Global.gameData.shareGameData = {};
            Global.gameData.shareGameData.players = {};

            fightUI.item.init();
            normalUI.visible = false;
            fightUI.visible = true;
        }



        function getGameDataToNetDBCallback(listData, type, value, code, successed) {
            console.debug("s_GetGameDataToNetDBCallback return OK!");

            var compPet = Qt.createComponent("Pet.qml");
            var pet;

            if(successed) {
                if (compPet.status === Component.Ready) {
                    for(var item in listData) {
                        if(listData[item] !== null && listData[item] !== "") {
                            pet = compPet.createObject(itemRoot, JSON.parse(listData[item]));
                            Global.gameData.arrayPets.push(pet);
                        }
                    }
                    if(Global.gameData.arrayPets.length === 0) {
                        if (compPet.status === Component.Ready) {
                            pet = compPet.createObject(itemRoot, {"test":1});
                            Global.gameData.arrayPets.push(pet);

                            var jsPet = GlobalJS.deepCopyObject(pet);
                            GameManager.sl_qml_SetGameDataToNetDB(jsPet, "", 1, GameManagerClass.DataType_JSon_Info);
                            //GameManager.sl_qml_InsertGameDataToNetDB(JSON.stringify(pet), 1, GameManagerClass.DataType_JSon_Info);
                            console.debug("[game]创建宠物信息中");
                        }
                    }
                    else
                        console.debug("[game]读取宠物信息完毕:",listData.length,listData);
                }
            }
            else
            {
                if(type === GameManagerClass.DataType_JSon_Info && value === 1) {

                    if(code === 0) {
                        if (compPet.status === Component.Ready) {
                            pet = compPet.createObject(itemRoot, {"test":1});
                            Global.gameData.arrayPets.push(pet);

                            var jsPet = GlobalJS.deepCopyObject(pet);
                            GameManager.sl_qml_SetGameDataToNetDB(jsPet, "", 1, GameManagerClass.DataType_JSon_Info);
                            //GameManager.sl_qml_InsertGameDataToNetDB(JSON.stringify(pet), 1, GameManagerClass.DataType_JSon_Info);
                            console.debug("[game]创建宠物信息中...");
                        }


                    }
                }

                else
                    console.error("[!game]s_GetGameDataToNetDBCallback ERROR:", type, value, code);
            }
        }



        //游戏开始，GameCore信号
        function gameStart(isStarted) {
            normalUI.item.pause();


            if(GameCore.socketInfo.isGroupMaster) {
                Global.gameFunctions.sendGameSyncAllData();
            }


            fightUI.item.start(isStarted);

        }

        //游戏结束,Manager数据处理完毕后,再调用显示
        function gameOver(status, code) {
            fightUI.item.gameOver();
            Global.gameData.shareGameData = {};
            Global.gameData.nGameFrameSendCount = 0;


            normalUI.item.resume();
            normalUI.visible = true;
            fightUI.visible = false;
            console.debug("[game]gameOver!")
        }




        function showExitBox() {
            menuEsc.show();
            menuEsc.focus = true;
        }

        function exit() {
            _private.showExitBox();
        }
    }






    Component.onCompleted: {
        console.debug("[game]QML组件初始化完毕")
    }
}
